import { computed } from 'vue';
import { userLoginStore, LoginStatus } from '@/stores/login';
import { useUserStore } from '@/stores/user';
import { createRouter, createWebHistory, RouteRecordRaw, NavigationGuardNext, RouteLocationNormalized, RouteLocationNormalizedLoaded } from 'vue-router';

import Home from '@/views/Main/Home/index.vue';
import News from '@/views/Main/News/index.vue';
import Links from '@/views/Main/Links/index.vue';
import AboutMe from '@/views/Main/AboutMe/index.vue';
import Detail from '@/views/Main/Detail/index.vue';
import noFindPage from '@/components/Error/404/index.vue';
import UserCenter from '@/views/Main/User/Center/index.vue';
import UserHome from '@/views/Main/User/Home/index.vue';

const routes: Array<RouteRecordRaw> = [
    {
        path: '/',
        name: '首页',
        component: Home,
    },{
        path: '/learn',
        name: 'learn',
        component: News,
        meta: {
          title: "学习笔记-羅氏博客"
        }
    },{
        path: '/life',
        name: 'life',
        component: News,
        meta: {
          title: "生活记录-羅氏博客"
        }
    },
    {
      path: '/seach',
      name: 'seach',
      component: News,
      meta: {
        title: "搜索-羅氏博客"
      }
    },
    {
      path: '/links',
      name: 'links',
      component: Links,
      meta: {
        title: "友情链接-羅氏博客"
      }
    },
    {
      path: '/aboutMe',
      name: 'aboutMe',
      component: AboutMe,
      meta: {
        title: "关于我-羅氏博客"
      }
    },{
      path: '/:pathMatch(.*)',
      name: '404',
      component: noFindPage,
      meta: {
        title: "404-羅氏博客"
      }
    },{
      path: '/blog/detail/:id',
      name: 'detail',
      component: Detail,
      meta: {
        title: "详情-羅氏博客"
      }
    },
    {
      path: '/users/:type',
      name: 'users',
      component: UserCenter,
      meta: {
        title: "用户中心-羅氏博客",
        requireAuth: true
      }
    },
    {
      path: '/u/:userId',
      name: 'u',
      component: UserHome,
      meta: {
        title: "个人主页-羅氏博客"
      }
    }
];

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes,
    scrollBehavior () {
      // 滚动到顶部
      return { top: 0 }
    }
});
   
router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalizedLoaded, next: NavigationGuardNext) => {

  const loginStore = userLoginStore();
  const userStore = useUserStore();

  // 是否已登录
  const isAuthenticated = computed<boolean>(() => loginStore.loginStatus === LoginStatus.Success);

  if (!isAuthenticated.value) {
      // 如果未登录且目标路由不是登录页，导航到首页
      if (to.meta.requireAuth) {
        // 打开登录框
        loginStore.isShowLoginBox = true;
        // 跳转首页
        next({ path: '/' })
      } else {
        next()
      }
  } else {
    // 获取登录用户信息
    userStore.getInfo();
    // 如果已登录或目标路由是登录页，继续导航
    next();
  }
});

export default router;